package com.oa.utils.jwt;

import com.alibaba.fastjson.JSON;
import com.oa.config.redis.RedisCache;
import com.oa.entity.domain.User;
import com.oa.entity.vo.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Objects;

/*
Jwt认证过滤器     在认证之前执行
1、获取token
2、解析token获取其中的userid
3、从redis中获取用户信息
4、存入SecurityContextHolder
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        filterChain.doFilter(request,response);
        // 1、获取token
        String token =request.getHeader("Authorization");
        System.out.println(token);
        //若没有token，表示是登录操作，直接放行
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //2、解析token获取其中的userid
        String userString;
        String userid;
        try {
            Claims claims = JwtUtils.parseToken(token);
//            userString=claims.getSubject();
//            User user = JSON.parseObject(userString, User.class);
//            userid=user.getId().toString();
              userid=claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token 非法");
        }
        // 3、从redis中获取用户信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = JSON.parseObject(JSON.toJSON(redisCache.getCacheObject(redisKey)).toString(),LoginUser.class);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("redis中用户信息不存在");
        }
        //4、存入SecurityContextHolder
        //TODO 获取权限信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //放行
        filterChain.doFilter(request,response);
    }
}
